#!/usr/bin/env bash
source "$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")/config"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_BASE_PATH/common/functions"
source "$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")/functions"

service-destroy-cmd() {
  #E destroy the service, it's data, and the running container
  #E dokku $PLUGIN_COMMAND_PREFIX:destroy lolipop
  #A service, service to run command against
  #F -f|--force, force destroy without asking for confirmation
  declare desc="delete the $PLUGIN_SERVICE service/data/container if there are no links left"
  local cmd="$PLUGIN_COMMAND_PREFIX:destroy" argv=("$@")
  [[ ${argv[0]} == "$cmd" ]] && shift 1
  declare SERVICE="$1" FORCE_FLAG="$2"

  [[ -z "$SERVICE" ]] && dokku_log_fail "Please specify a valid name for the service"
  verify_service_name "$SERVICE"
  SERVICE_ROOT="$PLUGIN_DATA_ROOT/$SERVICE"
  LINKS_FILE="$SERVICE_ROOT/LINKS"
  SERVICE_HOST_ROOT="$PLUGIN_DATA_HOST_ROOT/$SERVICE"
  SERVICE_NAME="$(get_service_name "$SERVICE")"

  [[ -s "$LINKS_FILE" ]] && dokku_log_fail "Cannot delete linked service"

  if [[ "$FORCE_FLAG" == "force" ]] || [[ "$FORCE_FLAG" == "-f" ]] || [[ "$FORCE_FLAG" == "--force" ]]; then
    DOKKU_APPS_FORCE_DELETE=1
  fi
  if [[ -z "$DOKKU_APPS_FORCE_DELETE" ]]; then
    dokku_log_warn "WARNING: Potentially Destructive Action"
    dokku_log_warn "This command will destroy $SERVICE $PLUGIN_SERVICE service."
    dokku_log_warn "To proceed, type \"$SERVICE\""
    echo ""

    read -rp "> " service_name
    if [[ "$service_name" != "$SERVICE" ]]; then
      dokku_log_warn "Confirmation did not match $SERVICE. Aborted."
      exit 1
    fi
  fi

  dokku_log_info2_quiet "Deleting $SERVICE"
  plugn trigger service-action pre-delete "$SERVICE"
  service_backup_unschedule "$SERVICE"
  service_container_rm "$SERVICE"

  dokku_log_verbose_quiet "Removing data"
  docker run --rm -v "$SERVICE_HOST_ROOT/data:/data" -v "$SERVICE_HOST_ROOT/$PLUGIN_CONFIG_SUFFIX:/config" "$PLUGIN_BUSYBOX_IMAGE" chmod 777 -R /config /data
  rm -rf "$SERVICE_ROOT"

  plugn trigger service-action post-delete "$SERVICE"
  dokku_log_info2 "$PLUGIN_SERVICE container deleted: $SERVICE"
}

service-destroy-cmd "$@"
